package com.celeritymq.monitor;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jms.JMSException;

import com.celeritymq.dispatcher.Dispatcher;
import com.celeritymq.logging.LoggerFactory;
import com.celeritymq.message.CelerityMessage;

public abstract class AbstractMonitor extends Thread implements Monitor {
	private Thread currentThread;
	protected Logger log = LoggerFactory.getLogger(getClass());
	protected Dispatcher dispatcher;

	protected AbstractMonitor(Dispatcher dispatcher) {
		setDaemon(true);
		this.dispatcher = dispatcher;
	}

	public void run() {
		currentThread = Thread.currentThread();
		while (true) {
			try {
				CelerityMessage msg = monitor();
				process(msg);
			} catch (InterruptedException e) {
				break;
			}
		}
	}

	@Override
	public void process(CelerityMessage msg) {
		log.log(Level.FINEST, "process [" + msg + "]");
		try {
			dispatcher.dispatch(msg);
		} catch (InterruptedException e) {
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void startMonitor() {
		start();
	}

	@Override
	public void stopMonitor() {
		currentThread.interrupt();
	}

}
